package com.hawk.eye.server.webhook;

import com.hawk.eye.api.webhook.IWebhookRequester;
import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.common.model.ChargeUser;
import com.hawk.eye.common.model.ServiceAlarmMessage;
import com.hawk.eye.common.model.ServiceConfigMessage;
import com.hawk.eye.common.utils.Base64Util;
import com.hawk.eye.common.utils.JsonUtil;
import com.hawk.eye.common.utils.StringUtil;
import com.hawk.eye.common.utils.http.OkHttpUtil;
import com.hawk.eye.framework.utils.ExceptionUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @className: DingTalkWebhookRequester
 * @description:
 * @author: salad
 * @date: 2023/10/4
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class DingTalkWebhookRequester implements IWebhookRequester {

    @Override
    public String identity() {
        return "钉钉";
    }

    @Override
    public void send(ServiceAlarmMessage sam) {
        Map<String, Object> json = new HashMap<>(16);
        Map<String, Object> text = new HashMap<>(16);
        Map<String, List<String>> phone = new HashMap<>(16);
        List<String> mob = new ArrayList<String>();
        Optional.ofNullable(sam.getServiceConfigMessage())
                .map(ServiceConfigMessage::getChargeUser)
                .map(ChargeUser::getPhone)
                .ifPresent(mob::add);
        json.put("msgtype", MsgType.TEXT.getCode());
        text.put("content", sam.getContent());
        phone.put("atMobiles", mob);
        json.put("text", text);
        json.put("at", phone);
        try {
            String webhook = sam.getWebhookConfigMessage().getWebhook();
            if (StringUtil.isNotBlank(sam.getWebhookConfigMessage().getSecret())) {
                long timestamp = System.currentTimeMillis();
                String sign = getSign(timestamp, sam.getWebhookConfigMessage().getSecret());
                webhook += "&timestamp=" + timestamp + "&sign=" + sign;
            }
            String resultAsString = OkHttpUtil.postJson(webhook, JsonUtil.toJson(json));
            log.info("[{}]响应结果:{}", identity(), resultAsString);
        } catch (Throwable e) {
            HawkEyeLogger.errorWithSkipSend(getClass(), identity() + "请求失败:{}", ExceptionUtil.getExceptionMessage(e));
        }

    }

    @Getter
    @AllArgsConstructor
    public enum MsgType {

        TEXT("text"),

        MD("markdown");

        private final String code;

    }

    private String getSign(Long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64Util.encode(signData)), "UTF-8");
    }

}
